require("dotenv").config();
const { ethers } = require("hardhat");
const fs = require("fs");
const path = require("path");
async function getOwner() {
  let [owner] = await ethers.getSigners();
  console.log("owner:" + owner.address);
  const balance = await ethers.provider.getBalance(owner.address);
  console.log("owner ETH 余额: " + ethers.formatEther(balance));
  return owner;
}
async function main() {
  console.log("开始获取部署账户...");
  owner = await getOwner();
  const balanceBefore = await ethers.provider.getBalance(owner.address);
  console.log("开始部署合约...");
  Token = await ethers.getContractFactory("TestToken");
  token = await Token.deploy(owner.address, owner.address);
  TestNFT = await ethers.getContractFactory("TestNFT");
  nft = await TestNFT.deploy(owner.address, token.target);
  console.log("部署完成");
  console.log("token:" + token.target);
  console.log("nft:" + nft.target);
  const balanceAfter = await ethers.provider.getBalance(owner.address);
  console.log(`花费ETH:${ethers.formatEther(balanceBefore - balanceAfter)}`);
  const deployments = {
    sepolia: {
      testToken: token.target,
      testNFT: nft.target,
    },
  };
  const deploymentsDir = path.join(__dirname, "../deployments");
  if (!fs.existsSync(deploymentsDir)) {
    fs.mkdirSync(deploymentsDir);
  }

  fs.writeFileSync(
    path.join(deploymentsDir, "Address.json"),
    JSON.stringify(deployments, null, 2)
  );

  console.log("合约地址已保存到 deployments/Address.json");
}

main()
  .then(() => process.exit(0))
  .catch((error) => {
    console.error(error);
    process.exit(1);
  });
